//
//  TimePicker2.m
//  TimePicker2Demo
//
//  Created by Winny Zhang on 2019/4/8.
//  Copyright © 2019 Winny Zhang. All rights reserved.
//

#import "YFTimePicker2.h"
#import "NSDate+YFExtension.h"

@interface YFTimePicker2 () <UIPickerViewDataSource, UIPickerViewDelegate>


/**
 内容 View
 */
@property (weak, nonatomic) IBOutlet UIView *contentView;

/**
 开始标签
 */
@property (weak, nonatomic) IBOutlet UILabel *startLabel;
/**
 结束标签
 */
@property (weak, nonatomic) IBOutlet UILabel *endLabel;

/**
 开始时间时钟 label
 */
@property (weak, nonatomic) IBOutlet UILabel *startHourLabel;
/**
 开始时间分钟 label
 */
@property (weak, nonatomic) IBOutlet UILabel *startMinLabel;
/**
 结束时间时钟 Label
 */
@property (weak, nonatomic) IBOutlet UILabel *endHourLabel;
/**
 结束时间分钟 label
 */
@property (weak, nonatomic) IBOutlet UILabel *endMinLabel;
/**
 开始时间 时钟选择器
 */
@property (weak, nonatomic) IBOutlet UIPickerView *startHourPicker;
/**
 开始时间 分钟选择器
 */
@property (weak, nonatomic) IBOutlet UIPickerView *startMinPicker;
/**
 结束时间 时钟选择器
 */
@property (weak, nonatomic) IBOutlet UIPickerView *endHourPicker;
/**
 结束时间 分钟选择器
 */
@property (weak, nonatomic) IBOutlet UIPickerView *endMinPicker;



/**
开始小时
 */
@property (nonatomic, strong) NSArray <NSString *> *startHours;
/**
 开始分钟
 */
@property (nonatomic, strong) NSArray <NSString *> *startMinutes;
/**
 结束小时
 */
@property (nonatomic, strong) NSArray <NSString *> *endHours;
/**
 结束分钟
 */
@property (nonatomic, strong) NSArray <NSString *> *endMinutes;

/**
 记录选中的开始小时
 */
@property (nonatomic, copy) NSString *selectedStartHour;

/**
 记录选中的开始分钟
 */
@property (nonatomic, copy) NSString *selectedStartMinute;

/**
 记录选中的结束小时
 */
@property (nonatomic, copy) NSString *selectedEndHour;

/**
 记录选中的结束分钟
 */
@property (nonatomic, copy) NSString *selectedEndMinute;

/**
 确定按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;


@end

@implementation YFTimePicker2

/**
 初始化
 
 */
+ (instancetype)timePicker2 {
    YFTimePicker2 *picker = [[NSBundle mainBundle] loadNibNamed:@"YFTimePicker2" owner:nil options:nil].firstObject;
    picker.frame = [UIScreen mainScreen].bounds;
    return picker;
}

- (void)show {
    self.alpha = 0;
    self.contentView.transform = CGAffineTransformMakeScale(0, 0);
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:1 options:(UIViewAnimationOptionCurveEaseOut) animations:^{
        self.alpha = 1;
        self.contentView.transform = CGAffineTransformMakeScale(1.7, 1.7);
        self.contentView.transform = CGAffineTransformMakeScale(1, 1);
    } completion:^(BOOL finished) {
        self.contentView.transform = CGAffineTransformIdentity;
    }];
}


- (void)dismiss {
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:1 options:(UIViewAnimationOptionCurveEaseOut) animations:^{
        self.alpha = 0;
        self.contentView.transform = CGAffineTransformMakeScale(0, 0);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        self.alpha = 1;
        self.contentView.transform = CGAffineTransformIdentity;
    }];
}


/**
 init方法初始化
 
 @param frame frame
 @return datePicker
 */
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self = [[NSBundle mainBundle] loadNibNamed:@"YFTimePicker2" owner:nil options:nil].firstObject;
        [self setupViews];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setupViews];
    }
    return  self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setupViews];
}

- (void)setupViews {
    
    self.contentView.layer.masksToBounds = YES;
    self.contentView.layer.cornerRadius = 10;
    
    self.startLabel.layer.masksToBounds = YES;
    self.startLabel.layer.cornerRadius = self.startLabel.frame.size.height * 0.5;
    self.endLabel.layer.masksToBounds = YES;
    self.endLabel.layer.cornerRadius = self.endLabel.frame.size.height * 0.5;
    
    self.startHourPicker.dataSource = self;
    self.startHourPicker.delegate = self;
    self.startMinPicker.dataSource = self;
    self.startMinPicker.delegate = self;
    
    self.endHourPicker.dataSource = self;
    self.endHourPicker.delegate = self;
    self.endMinPicker.dataSource = self;
    self.endMinPicker.delegate = self;
    
    [self.startHourPicker reloadAllComponents];
    [self.startMinPicker reloadAllComponents];
    [self.endHourPicker reloadAllComponents];
    [self.endMinPicker reloadAllComponents];
    
    self.selectedStartHour = [NSDate date].currentHour < 10 ? [NSString stringWithFormat:@"0%zd", [NSDate date].currentHour] : [NSString stringWithFormat:@"%zd", [NSDate date].currentHour];
    self.selectedStartMinute = [NSDate date].currentMinute < 10 ? [NSString stringWithFormat:@"0%zd", [NSDate date].currentMinute] : [NSString stringWithFormat:@"%zd", [NSDate date].currentMinute];
    self.selectedEndHour = @"00";
    self.selectedEndMinute = @"00";
    
    self.startHourLabel.text = [NSString stringWithFormat:@"%@", _selectedStartHour];
    self.startMinLabel.text = [NSString stringWithFormat:@"%@", _selectedStartMinute];
    self.endHourLabel.text = [NSString stringWithFormat:@"%@", _selectedEndHour];
    self.endMinLabel.text = [NSString stringWithFormat:@"%@", _selectedEndMinute];
    
    [self.startHourPicker selectRow: [self indexInArray:self.startHours value:_selectedStartHour] inComponent:0 animated:YES];
    [self.startMinPicker selectRow:[self indexInArray:self.startMinutes value:_selectedStartMinute] inComponent:0 animated:YES];
    [self.endHourPicker selectRow:0 inComponent:0 animated:YES];
    [self.endMinPicker selectRow:0 inComponent:0 animated:YES];
    
    [self.confirmButton setBackgroundImage:UIColor.blackColor.image forState:(UIControlStateNormal)];
    [self.confirmButton rounded:(UIRectCornerAllCorners) radius:5];
}

#pragma mark - UIPickerViewDataSource, UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(nonnull UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(nonnull UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    switch (pickerView.tag) {
        case 10060:
            return self.startHours.count;
            break;
        case 103600:
            return self.startMinutes.count;
            break;
        case 20060:
            return self.endHours.count;
            break;
        case 203600:
            return self.endMinutes.count;
            break;
        default:
            return 0;
            break;
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view {
    
    UIColor *lineColor = [UIColor colorWithRed:255/255.0 green:137/255.0 blue:128/255.0 alpha:1];
    
    // 隐藏横线
    ((UIView *)[pickerView.subviews objectAtIndex:1]).backgroundColor = lineColor;
    ((UIView *)[pickerView.subviews objectAtIndex:2]).backgroundColor = lineColor;
    
    // 显示内容
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0, 0, pickerView.frame.size.width, 35);
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentCenter;
    
    // 赋值
    switch (pickerView.tag) {
        case 10060:
            label.text = self.startHours[row];
            break;
        case 103600:
            label.text = self.startMinutes[row];
            break;
        case 20060:
            label.text = self.endHours[row];
            break;
        case 203600:
            label.text = self.endMinutes[row];
            break;
        default:
            break;
    }

    return label;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 35;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    switch (pickerView.tag) {
        case 10060:
            self.startHourLabel.text = self.startHours[row];
            self.selectedStartHour = self.startHours[row];
            break;
        case 103600:
            self.startMinLabel.text = self.startMinutes[row];
            self.selectedStartMinute = self.startMinutes[row];
            break;
        case 20060:
            self.endHourLabel.text = self.startMinutes[row];
            self.selectedEndHour = self.startMinutes[row];
            break;
        case 203600:
            self.endMinLabel.text = self.endMinutes[row];
            self.selectedEndMinute = self.endMinutes[row];
            break;
        default:
            break;
    }
    
    if (_completed) {
        _completed(_selectedStartHour, _selectedStartMinute, _selectedEndHour, _selectedEndMinute);
    }
}



#pragma mark - lazy Load
- (NSArray <NSString *> *)startHours {
    if (!_startHours) {
        NSMutableArray *hours = [NSMutableArray arrayWithCapacity:24];
        NSInteger hour = 0;
        for (int i = 0; i < 24; i++) {
            if (hour < 10) {
                [hours addObject:[NSString stringWithFormat:@"0%zd", hour]];
            } else {
                [hours addObject:[NSString stringWithFormat:@"%zd", hour]];
            }
            hour += 1;
        }
        _startHours = hours;
    }
    return _startHours;
}

- (NSArray <NSString *> *)startMinutes {
    if (!_startMinutes) {
        NSMutableArray *minutes = [NSMutableArray arrayWithCapacity:60];
        NSInteger minute = 0;
        for (int i = 0; i < 60; i++) {
            if (minute < 10) {
                [minutes addObject:[NSString stringWithFormat:@"0%zd", minute]];
            } else {
                [minutes addObject:[NSString stringWithFormat:@"%zd", minute]];
            }
            minute += 1;
        }
        _startMinutes = minutes;
    }
    return _startMinutes;
}

- (NSArray <NSString *> *)endHours {
    if (!_endHours) {
        NSMutableArray *hours = [NSMutableArray arrayWithCapacity:24];
        NSInteger hour = 0;
        for (int i = 0; i < 24; i++) {
            if (hour < 10) {
                [hours addObject:[NSString stringWithFormat:@"0%zd", hour]];
            } else {
                [hours addObject:[NSString stringWithFormat:@"%zd", hour]];
            }
            hour += 1;
        }
        _endHours = hours;
    }
    return _endHours;
}

- (NSArray <NSString *> *)endMinutes {
    if (!_endMinutes) {
        NSMutableArray *minutes = [NSMutableArray arrayWithCapacity:60];
        NSInteger minute = 0;
        for (int i = 0; i < 60; i++) {
            if (minute < 10) {
                [minutes addObject:[NSString stringWithFormat:@"0%zd", minute]];
            } else {
                [minutes addObject:[NSString stringWithFormat:@"%zd", minute]];
            }
            minute += 1;
        }
        _endMinutes = minutes;
    }
    return _endMinutes;
}

#pragma mark - 获取元素在数组中的位置
- (NSInteger)indexInArray:(NSArray <NSString *> *)array value:(NSString *)value {
    __block NSInteger index = 0;
    [array enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (value.integerValue == obj.integerValue) {
            index = idx;
        }
    }];
    return index;
}


#pragma mark - 按钮点击方法

- (IBAction)confirmButtonClicked:(id)sender {
    
    if (_completed) {
        _completed(_selectedStartHour, _selectedStartMinute, _selectedEndHour, _selectedEndMinute);
    }
    [self dismiss];
}




@end
